import util from '@/libs/util';
import Cookies from 'js-cookie';
import domtoimage from 'dom-to-image';
import backgroundUrl from '@/images/invoice_background.jpg';

export default {
    name: 'exportable-table',
    data () {
        return {
            baseuser: JSON.parse(Cookies.get('baseUser')),
            formData: {},
            makeTemplate: {
                sprites: []
            },
            model: null,
            imgScale: 1,
            $previewContainer: null,
            backgroundUrl: backgroundUrl,
            bill: {},
            test: ''
        };
    },
    mounted () {
        this.setScale();
        this.bill = this.$route.params.data;
        util.ajax.post('/busine/model/findByOrg', util.toFormData({
            organizeid: this.baseuser.orgId
        })).then(res => {
            let data = res.data.data;
            if (data && data.length > 0) {
                this.makeTemplate = JSON.parse(data[0].content);
                let sprites = this.makeTemplate.sprites;
                sprites.forEach((citem) => {
                    if (citem.name && citem.name === 'name') {
                        citem.content = citem.content.replace(citem.text, this.bill['student_name']);
                    } else if (citem.name && citem.name === 'reserve_no') {
                        citem.content = citem.content.replace(citem.text, this.bill['billcode']);
                    } else if (citem.name && citem.name === 'amt') {
                        citem.content = citem.content.replace(citem.text, this.bill['real_amt']);
                    } else if (citem.name && citem.name === 'charge_date') {
                        citem.content = citem.content.replace(citem.text, util.getDate(this.bill['createtime'], 'time'));
                    } else if (citem.name && citem.name === 'charge_type') {
                        let payType = this.bill.payType;
                        let text = '';
                        if (payType == 1) {
                            text = '现金';
                        } else if (payType == 14) {
                            text = '微信';
                        }
                        citem.content = citem.content.replace(citem.text, text);
                    }
                });
            } else {
                this.$Message.warning('请先设置发票模板');
            }
        });
    },
    methods: {
        setScale () {
            let _this = this;
            this.$previewContainer = this.$el.querySelector('.make-preview');
            let rect = this.$previewContainer.getBoundingClientRect();
            let clientWidth = rect.width - 20;
            let clientHeight = rect.height - 20;

            var img = new Image();
            img.src = this.backgroundUrl;
            img.onload = function () {
                let imgWidth = img.width;
                let imgHidth = img.height;
                if (clientWidth / clientHeight > imgWidth / imgHidth) {
                    _this.imgScale = clientHeight / imgHidth;
                } else {
                    _this.imgScale = clientWidth / imgWidth;
                }
            };
        },
        save () {
            this.$Spin.show({
                render: (h) => {
                    return h('div', [
                        h('Icon', {
                            'class': 'demo-spin-icon-load',
                            props: {
                                type: 'load-c',
                                size: 30
                            }
                        }),
                        h('div', '发票保存中请稍等...')
                    ]);
                }
            });
            this.generate();
        },
        generate () {
            let image = this.$refs.image;
            let formData = {};
            this.$nextTick().then(() => {
                domtoimage.toJpeg(image, {
                    quality: 1
                }).then((dataUrl) => {
                    util.ajax.post('/upload/uploadPrize', util.toFormData({
                        dataUrl: dataUrl
                    })).then(res => {
                        if (res.data.message === 'SUCCESS') {
                            formData.invoicePath = res.data.data.imgPath;
                            formData.id = this.bill.id;
                            util.ajax.post('/busine/bill/update', util.toFormData(formData)).then(res => {
                                if (res.data.message === 'SUCCESS') {
                                    this.$Message.success('保存成功！');
                                    this.$Spin.hide();
                                    this.back(formData.id);
                                }
                            });
                        } else {
                            this.$Message.warning(res.data.message || '未知错误！');
                        }
                    });
                });
            });
        },
        getSpriteStyle (sprite) {
            let style = {
                transform: `translateX(${sprite.x * this.imgScale}px) translateY(${sprite.y * this.imgScale}px)`
            };
            if (sprite.type === 'picture') {
                style.width = `${sprite.width * this.imgScale}px`;
                style.height = `${sprite.height * this.imgScale}px`;
            }
            return style;
        },
        replaceText (name, text) {
            let currSprite = this.makeTemplate.sprites;
            currSprite.forEach((item) => {
                if (item.name === name) {
                    item.content = item.content.replace(item.text, text);
                    item.text = text;
                }
            });
        },
        back (billId) {
            let entry = this.$route.params.entry;
            if (entry == 1) {
                this.$store.commit('removeTag', 'invoicecreate');
                this.$router.push({
                    path: 'trainingmanagement',
                    name: 'trainingmanagement',
                    params: {
                        entry: entry,
                        billId: billId
                    }
                });
            } else {
                this.$store.commit('removeTag', 'invoicecreate');
                this.$router.push({
                    path: 'trainingmanagement',
                    name: 'trainingmanagement',
                    params: {
                        entry: entry,
                        billId: billId
                    }
                });
            }
        }
    }
};
